<?php

namespace Modules\Agent\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use \Modules\User\Entities\User;

use Validator;
use ThrowException;
use Auth;

class InviteeController extends Controller
{
    // 我邀请的用户列表
    public function index(Request $req)
    {
        $options = $req->all();

        $user = Auth::requireLoginUser();

        $user->updateInviteeCount();

        $options = [
            'per_page' => $req->input('per_page', 10),
            'page' => $req->input('page', 1),
        ];

        // 直接
        if ($req->input('type') === 'direct') {
            $options['scopes'] = [
                'directInviteBy' => $user
            ];
        }
        // 间接
        elseif ($req->input('type') === 'indirect') {
            $options['scopes'] = [
                'indirectInviteBy' => $user
            ];
        }
        // 全部
        else {
            $options['scopes'] = [
                'inviteBy' => $user
            ];
        }

        // 搜索手机号
        if ($req->input('phone')) {
            $options['where']['phone'] = $req->phone;
        }

        // 邀请时间
        $sortBy = $req->input('sort', 'time_desc');

        $sortByMap = [
            'time_desc' => [
                'invited_at' => 'desc'
            ],
            'time_asc' => [
                'invited_at' => 'asc'
            ],
            'paid_money_desc' => [
                'paid_money_total' => 'desc',
                'invited_at' => 'desc'
            ],
            'paid_money_asc' => [
                'paid_money_total' => 'asc',
                'invited_at' => 'desc'
            ],
            'brokerage_desc' => [
                'first_money_brokerage' => 'desc',
                'invited_at' => 'desc'
            ],
            'brokerage_asc' => [
                'first_money_brokerage' => 'asc',
                'invited_at' => 'desc'
            ],
        ];

        $options['order_by'] = @$sortByMap[$sortBy] ?: ThrowException::Conflict('错误的排序规则');

        $options['only'] = [
            'id',
            'uuid',
            'name',
            'headimg',
            'phone',
            'created_at',
            'paid_money_total',
            'paid_score_total',
            'money_brokerage',
            'score_brokerage',
            'invite_base_reward',
        ];

        $list = User::getList($options);

        $list->each(function ($item) use ($user) {
            // 如果是直接粉丝
            if ($item->isDirectInvitee($user)) {
                $item->money_brokerage = $item->first_money_brokerage;
                $item->score_brokerage = $item->first_score_brokerage;
            }
            else {
                $item->money_brokerage = $item->second_money_brokerage;
                $item->score_brokerage = $item->second_score_brokerage;
            }
        });

        return $list->generateListResponse();
    }

}
